<template>
  <div class="box" ref="box">
    <div>
      <el-button @click="startCamera">开启视频</el-button>
      <el-button @click="closeCamera">关闭视频</el-button>
    </div>
    <video ref="video" autoplay muted></video>
  </div>
</template>
<script>
export default {
  data() {
    return {
      stream: null,
    };
  },
  methods: {
    startCamera() {
      navigator.mediaDevices
        .getUserMedia({
          audio: false,
          video: true,
        })
        .then((stream) => {
          // var videoTracks = stream.getVideoTracks();
          // console.log('Got stream with constraints:', constraints);
          // console.log('Using video device: ' + videoTracks[0].label);
          // stream.onended = function() {
          //   console.log('Stream ended');
          // };
          // window.stream = stream; // make variable available to browser console
          this.stream = stream;
          this.$refs.video.srcObject = stream;
        })
        .catch(function (error) {
          if (error.name === "ConstraintNotSatisfiedError") {
            alert("你的摄像头不支持该分辨率");
          } else if (error.name === "PermissionDeniedError") {
            alert("请打开摄像头权限");
          } else if (error.name === "NotFoundError") {
            alert("找不到设备");
          }
        });
    },
    closeCamera() {
      this.stream.getTracks()[0].stop();
      this.$refs.video.srcObject = null;
    },
  },
};
</script>
<style scoped lang="scss">
.box {
  video {
    background: #000;
  }
}
</style>